/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.cristina.attention.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cristina.attention.AttentionUser;
import com.cristina.attention.config.bean.LoginProperties;
import com.cristina.attention.exception.BadRequestException;
import com.cristina.attention.exception.EntityNotFoundException;
import com.cristina.attention.feign.UserFeignService;
import com.cristina.attention.service.dto.JwtUserDto;
import com.cristina.attention.utils.BeanDynamicAddUtil;
import com.cristina.attention.utils.R;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@AllArgsConstructor
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final LoginProperties loginProperties;
    private final UserFeignService userFeignService;

    public void setEnableCache(boolean enableCache) {
        this.loginProperties.setCacheEnable(enableCache);
    }

    /**
     * 用户信息缓存
     *
     * @see {@link UserCacheClean}
     */
    static Map<String, JwtUserDto> userDtoCache = new ConcurrentHashMap<>();

    @Override
    public JwtUserDto loadUserByUsername(String username) {
        boolean searchDb = true;
        JwtUserDto jwtUserDto = null;
        if (loginProperties.isCacheEnable() && userDtoCache.containsKey(username)) {
            jwtUserDto = userDtoCache.get(username);
        }
        if (searchDb) {
            AttentionUser user = new AttentionUser();
            try {
                R result = userFeignService.findUserByUsername(username);
                String jsonString = JSON.toJSONString(result.getData());
                JSONObject jsonObject = JSON.parseObject(jsonString);
                user.setEnabled(jsonObject.getBoolean("enabled"));
                user.setPassword("$2a$10$b5obkHucjCgYGsprHCEjfeNOHSbbQzsWWm.HmMdc9rPfetGa09V/i");
                user = (AttentionUser) BeanDynamicAddUtil.getTarget(user, jsonObject);
            } catch (EntityNotFoundException e) {
                // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
                throw new UsernameNotFoundException("", e);
            }
            if (user == null) {
                throw new UsernameNotFoundException("");
            } else {
                if (!user.getEnabled()) {
                    throw new BadRequestException("账号未激活！");
                }
                jwtUserDto = new JwtUserDto(
                        user,
                        null,
                        mapToGrantedAuthorities()
                );
                userDtoCache.put(username, jwtUserDto);
            }
        }
        return jwtUserDto;
    }

    private List<GrantedAuthority> mapToGrantedAuthorities() {
        Set<String> permissions = new HashSet<>();
        permissions.add("admin");
        return permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }
}
